package org.server;

import java.util.Iterator;
import java.util.Random;
import java.util.Vector;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import com.sun.org.apache.xml.internal.serialize.XMLSerializer;

public class ServerClientHandler {

	public static void main(String[] args) {
		
		//QFileHandler.writeToFile("src\\org\\server\\file.txt", "ahmdaliSTring");
		//System.out.println("i am done");
		new ServerClientHandler();
	}
	private String filePath = "src\\org\\server\\file.txt";
	private Vector<Client> currentClientList;
	public ServerClientHandler()
	{
		///addClient("ahmd", "abc");
		currentClientList = getServerClients();
		//Client[] clients = new Client[2];
		//clients[0] = new Client("ahmd",45);
		//clients[1] = new Client("moha",56);
		//writeClients(clients);
		//addClient("ahmd", "ahmd");
		addClient("taha", "taha");
		addClient("roby", "roby");
		//System.out.println(isClientExists("taha", "yoy"));
		System.out.println("i am done");
		
	}
	private Vector<Client> getServerClients()
	{
		Vector<Client> foundClients = new Vector<Client>();
		try {
			
			DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
		    DocumentBuilder docBuilder = dbfac.newDocumentBuilder();
		    Document doc = docBuilder.parse(filePath);
		    NodeList list = doc.getElementsByTagName("client");
		    int len  = list.getLength();
		    for (int i = 0; i < len; i++) {
				Client temp  = new Client();
				temp.setUsername(list.item(i).getFirstChild().getTextContent());
				temp.setPasswordHash(Integer.parseInt(list.item(i).getLastChild().getTextContent()));
				foundClients.add(temp);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return foundClients;
	}
	private boolean writeClients()
	{
		try {
		    DocumentBuilderFactory factory = 
		      DocumentBuilderFactory.newInstance();
		    DocumentBuilder loader = factory.newDocumentBuilder();

		    Document document = loader.newDocument();

		    Element root = document.createElement("clients");
		    
		    for (int i = 0; i < currentClientList.size(); i++) {
		    	Element client = document.createElement("client");
			    root.appendChild(client);
			    Element usernameElement = document.createElement("Username");
			    usernameElement.appendChild(document.createTextNode(currentClientList.get(i).getUsername()));
			    client.appendChild(usernameElement);
			    Element passwordElement = document.createElement("Password");
			    passwordElement.appendChild(document.createTextNode(String.valueOf(currentClientList.get(i).getPasswordHash())));
			    client.appendChild(passwordElement);	
			}
		    document.appendChild(root);
		    XMLSerializer serializer = new XMLSerializer();
		    serializer.setOutputCharStream(
		      new java.io.FileWriter(filePath));
		    serializer.serialize(document);

		    } catch (Exception ex) {
		      ex.printStackTrace();
		      return false;
		    }
		return true;
	}
	public boolean addClient(String username,String password)
	{
		int passHash = password.hashCode();
		Random rand = new Random(passHash);
		passHash +=  rand.nextInt() % rand.nextInt();
		Client newClient = new Client(username,passHash);
		currentClientList.add(newClient);
		writeClients();
		return false;
	}
	
	public boolean isClientExists(String username,String password)
	{
		int passHash = password.hashCode();
		Random rand = new Random(passHash);
		passHash +=  rand.nextInt() % rand.nextInt();
		Iterator<Client> iter = currentClientList.iterator();
		while(iter.hasNext())
		{
			Client item = iter.next();
			if(item.getUsername().equals(username) && item.getPasswordHash() == passHash)
				return true;
		}
		return false;
	}
}
